package com.erf.handler.server;

import com.erf.message.ActiveTest;
import com.erf.tools.SequenceUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhangzy
 * @date 2022/7/6
 */
@Slf4j
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {
    private int readRetryTimes = 3;
    private int lossConnectCount = 0;
    public HeartBeatServerHandler(int readRetryTimes){
        this.readRetryTimes = readRetryTimes;
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String user = ctx.channel().attr(LoginRequestHandler.KEY).get();
        if (user != null) {
            lossConnectCount = 0;
        }
        ctx.fireChannelRead(msg);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        String user = ctx.channel().attr(LoginRequestHandler.KEY).get();
        if (user == null) {
            ctx.channel().close();
        } else {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleState.READER_IDLE) {
                    lossConnectCount++;
                    if (lossConnectCount > readRetryTimes - 1) {
                        log.info("channel：" + ctx.channel().id().asShortText() + "由于不活跃被关闭！");
                        ctx.channel().close();
                    } else {
                        ActiveTest activeTest = new ActiveTest();
                        ctx.channel().writeAndFlush(activeTest);
                    }
                }
            } else {
                super.userEventTriggered(ctx, evt);
            }
        }
    }
}
